<!DOCTYPE html>
<html>
<head>
    <title>Title</title>
</head>
<body onload="draw()">

<div id="container">
    <canvas id="mycanvas" width="150" height="150">Your Browser does not support Canvas, please upgrade</canvas>
</div>

<script>
    // save和restore():保存与恢复状态，恢复时是恢复到save()时的状态
    function draw() {
        const canvas = document.getElementById('mycanvas');
        const ctx = canvas.getContext('2d');
        ctx.fillRect(0, 0, 150, 150);
        ctx.save();
        ctx.fillStyle = '#09F';
        ctx.fillRect(15, 15, 120, 120);
        ctx.save();
        ctx.fillStyle = '#FFF';
        ctx.globalAlpha = 0.5;    
        ctx.fillRect(30, 30, 90, 90);
        
        // 回到上一个状态
        ctx.restore();
        ctx.fillRect(45, 45, 60, 60);
        // 回到最初的状态
        ctx.restore();
        ctx.fillRect(45, 45, 60, 60);
    }
</script>
</body>
</html>